import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { codeInspectorPlugin } from "code-inspector-plugin";
import { createHtmlPlugin } from "vite-plugin-html";
import { execSync } from "child_process";

// 获取当前分支名称
const getGitBranch = () => {
  try {
    return execSync("git rev-parse --abbrev-ref HEAD").toString().trim();
  } catch (e) {
    return "unknown";
  }
};

// 获取当前打包时间
const getBuiltTime = () => {
  const now = new Date();
  const Y = now.getFullYear();
  const M = now.getMonth() + 1;
  const D = now.getDate();
  const h = now.getHours();
  const m = now.getMinutes();
  const s = now.getSeconds();
  return `${Y}-${M.toString().padStart(2, "0")}-${D.toString().padStart(
    2,
    "0"
  )} ${h.toString().padStart(2, "0")}:${m.toString().padStart(2, "0")}:${s
    .toString()
    .padStart(2, "0")}`;
};

// https://vite.dev/config/
export default defineConfig({
  base: "./",

  envDir: "./env",

  resolve: {
    alias: {
      "@": "/src",
    },
  },

  plugins: [
    vue(),

    codeInspectorPlugin({
      bundler: "vite",
    }),

    createHtmlPlugin({
      minify: true,
      inject: {
        tags: [
          {
            injectTo: "head-prepend",
            tag: "meta",
            attrs: {
              charset: "UTF-8",
              "data-builtTime": getBuiltTime(),
              "data-branchName": getGitBranch(),
            },
          },
        ],
      },
    }),
  ],

  server: {
    port: 11000,

    proxy: {
      "/API/api": {
        target: "http://localhost:9000", // 后端服务器地址
        changeOrigin: true, // 是否改变请求源
        rewrite: (path) => path.replace(/^\/API/, ""), // 可选，重写路径
      },

      "/file": {
        target: "http://localhost:9100", // 后端服务器地址
        changeOrigin: true, // 是否改变请求源
        // rewrite: (path) => path.replace(/^\/file/, "file"), // 可选，重写路径
      },
    },
  },
});
